import request from '@/Newapi/request/request'
import { AdminUserType, UserQueryParams, UserEditParams } from '@/api/model/adminUserModel'

// 用户管理相关接口前缀
const API_PREFIX = '/static';

// 用户管理API类
export class AdminUserService {
  // 获取用户列表
  static async getUserList(params: UserQueryParams) {
    const { page, pageSize, where } = params
    
    // 处理where条件：过滤空值 + 转换数字类型
    const processedWhere = where ? Object.fromEntries(
      Object.entries(where)
        .filter(([_, value]) => value !== undefined && value !== '')
        .map(([key, value]) => {
          // 转换数字类型字段
          if (['gender', 'id'].includes(key) && typeof value === 'string') {
            return [key, Number(value)]
          }
          return [key, value]
        })
    ) : undefined
  
    const queryParams: Record<string, any> = {
      page,
      pageSize
    };
    
    if (processedWhere) {
      queryParams.where = JSON.stringify(processedWhere);
    }
    
    console.log('请求参数:', queryParams);
    
    try {
      const response = await request.get(`${API_PREFIX}/user/list`, queryParams);
      return response;
    } catch (error) {
      console.error('获取用户列表失败:', error);
      return { data: [], total: 0 };
    }
  }

  // 获取用户详情
  static async getUserDetail(id: number) {
    try {
      const response = await request.get(`${API_PREFIX}/user/${id}`);
      return response;
    } catch (error) {
      console.error('获取用户详情失败:', error);
      throw error;
    }
  }

  // 添加用户
  static async addUser(params: UserEditParams) {
    console.log('添加用户参数:', params);
    
    try {
      const response = await request.post(`${API_PREFIX}/user/add`, params);
      return response;
    } catch (error) {
      console.error('添加用户失败:', error);
      throw error;
    }
  }

  // 编辑用户
  static async updateUser(id: number, params: UserEditParams) {
    // 确保params中包含id字段
    const updateParams = { 
      ...params, 
      id 
    };
    console.log('更新用户参数:', updateParams);
    
    try {
      const response = await request.post(`${API_PREFIX}/user/update`, updateParams);
      return response;
    } catch (error) {
      console.error('更新用户失败:', error);
      throw error;
    }
  }

  // 删除用户
  static async deleteUser(id: number) {
    try {
      const response = await request.delete(`${API_PREFIX}/user/${id}`);
      return response;
    } catch (error) {
      console.error('删除用户失败:', error);
      throw error;
    }
  }

  // 批量删除用户
  static async batchDeleteUsers(ids: number[]) {
    console.log('批量删除用户参数:', { id: ids });
    
    try {
      const response = await request.delete(`${API_PREFIX}/user/del`, { id: ids });
      return response;
    } catch (error) {
      console.error('批量删除用户失败:', error);
      throw error;
    }
  }

  // 重置用户密码
  static async resetPassword(id: number, newPassword?: string) {
    try {
      const response = await request.put(`${API_PREFIX}/user/${id}/reset-password`, { password: newPassword });
      return response;
    } catch (error) {
      console.error('重置用户密码失败:', error);
      throw error;
    }
  }

  // 获取用户组列表
  static async getUserGroups() {
    console.log('正在请求用户组列表API');
    
    try {
      const response = await request.get(`${API_PREFIX}/role/group`);
      return response;
    } catch (error) {
      console.error('获取用户组列表失败:', error);
      throw error;
    }
  }

  // 获取所有管理员用户列表
  static async getAllAdminUsers() {
    console.log('正在请求所有管理员用户列表');
    
    try {
      const response = await request.get(`${API_PREFIX}/user/all`);
      return response;
    } catch (error) {
      console.error('获取所有管理员用户列表失败:', error);
      throw error;
    }
  }
}